package com.aaa.doctor.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.aaa.doctor.dao.*;
import com.aaa.doctor.feign.DeptFegin;
import com.aaa.doctor.feign.UserFeign;
import com.aaa.doctor.service.PatientService;
import com.aaa.doctor.utils.IdWorker;
import com.aaa.doctor.vo.Dvo;
import com.aaa.doctor.vo.PatientVo;
import com.aaa.entity.*;
import com.aaa.utils.TokenUtils;
import com.aaa.utils.WebUtil;
import com.aaa.vo.Result;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class PatientServiceImpl implements PatientService {

    @Resource
    private PatientDao patientDao;

    @Autowired
    private PatientFileDao patientFileDao;

    @Autowired
    private CareHistoryDao careHistoryDao;

    /**
     * 分页查询患者库信息
     * 模糊查询姓名以及精确查询电话号码和身份证号
     * @param currentPage
     * @param pageSize
     * @param patientVo
     * @return
     */
    @Override
    public Result<IPage<Patient>> getAllPatient(Integer currentPage, Integer pageSize, PatientVo patientVo) {
        IPage<Patient> page = new Page<>(currentPage,pageSize);
        QueryWrapper<Patient> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(patientVo.getName())){
            wrapper.like("name",patientVo.getName());
        }
        if (StringUtils.hasText(patientVo.getPhone())){
            wrapper.eq("phone",patientVo.getPhone());
        }
        if (Objects.nonNull(patientVo.getIdCard())){
            wrapper.eq("id_card",patientVo.getIdCard());
        }
        //调用dao层接口方法--mybatisPuls自带方法
        IPage<Patient> patientIPage = patientDao.selectPage(page, wrapper);
        return new Result<>(200,"查询患者库成功",patientIPage);
    }

    /**
     * 根据patientID查询患者库
     * @param patientId
     * @return
     */
    @Override
    public Result<Patient> getInfoByPatientId(String patientId) {
        QueryWrapper<Patient> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(patientId)){
            wrapper.eq("patient_Id",patientId);
        }
        Patient patient = patientDao.selectOne(wrapper);
        return new Result<>(200,"查询患者库成功",patient);
    }

    /**
     * 根据身份证号加载患者信息
     * @param idCard
     * @return
     */
    @Override
    public Result<Patient> getInfoByidCard(String idCard) {
        QueryWrapper<Patient> wrapper = new QueryWrapper<>();
        if (StringUtils.hasText(idCard)) {
            wrapper.eq("id_card",idCard);
        }
        Patient ByidCardAll = patientDao.selectOne(wrapper);
        return new Result<>(200,"根据身份证号加载信息成功",ByidCardAll);
    }

    /**
     * 根据患者ID查询患者信息、档案信息、病历信息
     * @param patientId
     * @return
     */
    @Override
    public Result<Map<String,Object>> getAllByPatientId(String patientId) {
        QueryWrapper<Patient> wrapper = new QueryWrapper<>();
        wrapper.eq("patient_id",patientId);
        Patient patient = patientDao.selectOne(wrapper);

        QueryWrapper<PatientFile> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("patient_id",patientId);
        PatientFile patientFile = patientFileDao.selectOne(wrapper1);

        QueryWrapper<CareHistory> wrapper2 = new QueryWrapper<>();
        wrapper2.eq("patient_id",patientId);
        List<CareHistory> careHistories = careHistoryDao.selectList(wrapper2);

        Map<String, Object> map = new HashMap<>();
        map.put("patientObj",patient);
        map.put("patientFileObj",patientFile);
        map.put("careHistoryObjList",careHistories);
        return new Result<>(200,"查询患者信息、档案信息、病历信息成功",map);
    }

    @Autowired
    private UserFeign userFeign;


    @Autowired
    private RegistrationDao registrationDao;

    /**
     * 给患者挂号
     * @param patient
     * @param registration
     * @param a3
     * @return
     */
    @Override
    public Result<String> addRegistration(Patient patient, Registration registration, Dvo a3) {

        //根据当前患者的身份证号，查询是否在患者库里已经有信息
        QueryWrapper<Patient> wrapper = new QueryWrapper<>();
        // 指定生成患者id
        IdWorker idWorker = new IdWorker();
        wrapper.eq("id_card", patient.getIdCard());
        //根据身份证查询患者库是否有这个人
        Patient userInfo = patientDao.selectOne(wrapper);
        // 如果为空，则走这一步
        if (userInfo == null) {
            long id = idWorker.nextId();
            String Pid = "HZ" + id;
            patient.setPatientId(Pid);
            patient.setCreateTime(LocalDateTime.now());
            patientDao.insert(patient);
        }
        //雪花算法
        long GH = idWorker.nextId();
        String Gid = "GH" + GH;
        registration.setPatientId(patient.getPatientId());
        registration.setRegistrationId(Gid);
        registration.setPatientName(patient.getName());
        // 在token里获取手机号
        HttpServletRequest request = WebUtil.getRequest();
        String token = request.getHeader("token");
        Map<String, Object> tokenInfo = TokenUtils.getInfo(token);
        String phone = tokenInfo.get("username").toString();
        User user = userFeign.getByUsername(phone);
        //获取接诊医生
        String usernameById = userFeign.getUsernameById(a3.getUserId());
        registration.setDoctorName(usernameById);
        registration.setUserId(a3.getUserId());
        // 时间类型转换
        LocalDateTime now = LocalDateTime.now();
        registration.setCreateTime(now);
        registration.setCreateBy(user.getUserName());
        registration.setSubsectionType(a3.getSchedulingType());
        registration.setDeptId(a3.getDeptId());
        registration.setRegistrationItemId(a3.getRegItemId());
        registration.setRegistrationAmount(a3.getRegItemAmount());
        registration.setVisitDate(a3.getVisitDate());
        registration.setSubsectionType(a3.getSubsectionType());
         // 获取当前挂号部门的号数
        Registration registrationNumber = registrationDao.getregistrationNumber(registration.getDeptId());
        if (registrationNumber.getRegistrationNumber() ==0 || registrationNumber.getRegistrationNumber() == null){
            registration.setRegistrationNumber(1);
        }else{
            // 所挂号数+1
            Integer number = (registrationNumber.getRegistrationNumber() +1);
            registration.setRegistrationNumber(number);
        }

        registration.setRegistrationStatus("0");
        int insert = registrationDao.insert(registration);
        if (insert > 0) {
            return new Result<String>(200, "挂号成功", registration.getRegistrationId());
        }
        return new Result<>("挂号失败");
    }
}
